Merge "Improved/added parameter documentation"
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2 /**
3 * @defgroup FileRepo File Repository
4 *
5 * @brief This module handles how MediaWiki interacts with filesystems.
6 *
7 * @details
8 */
9
10 /**
11 * Base code for file repositories.
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
27 *
28 * @file
29 * @ingroup FileRepo
30 */
31
32 /**
33 * Base class for file repositories
34 *
35 * @ingroup FileRepo
36 */
37 class FileRepo {
38 const DELETE_SOURCE = 1;
39 const OVERWRITE = 2;
40 const OVERWRITE_SAME = 4;
41 const SKIP_LOCKING = 8;
42
43 /** @var FileBackend */
44 protected $backend;
45 /** @var Array Map of zones to config */
46 protected $zones = array();
47
48 var $thumbScriptUrl, $transformVia404;
49 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
50 var $fetchDescription, $initialCapital;
51 var $pathDisclosureProtection = 'simple'; // 'paranoid'
52 var $descriptionCacheExpiry, $url, $thumbUrl;
53 var $hashLevels, $deletedHashLevels;
54
55 /**
56 * Factory functions for creating new files
57 * Override these in the base class
58 */
59 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
60 var $oldFileFactory = false;
61 var $fileFactoryKey = false, $oldFileFactoryKey = false;
62
63 /**
64 * @param $info array|null
65 * @throws MWException
66 */
67 function __construct( array $info = null ) {
68 // Verify required settings presence
69 if(
70 $info === null
71 || !array_key_exists( 'name', $info )
72 || !array_key_exists( 'backend', $info )
73 ) {
74 throw new MWException( __CLASS__ . " requires an array of options having both 'name' and 'backend' keys.\n" );
75 }
76
77 // Required settings
78 $this->name = $info['name'];
79 if ( $info['backend'] instanceof FileBackend ) {
80 $this->backend = $info['backend']; // useful for testing
81 } else {
82 $this->backend = FileBackendGroup::singleton()->get( $info['backend'] );
83 }
84
85 // Optional settings that can have no value
86 $optionalSettings = array(
87 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
88 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
89 'scriptExtension'
90 );
91 foreach ( $optionalSettings as $var ) {
92 if ( isset( $info[$var] ) ) {
93 $this->$var = $info[$var];
94 }
95 }
96
97 // Optional settings that have a default
98 $this->initialCapital = isset( $info['initialCapital'] )
99 ? $info['initialCapital']
100 : MWNamespace::isCapitalized( NS_FILE );
101 $this->url = isset( $info['url'] )
102 ? $info['url']
103 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
104 if ( isset( $info['thumbUrl'] ) ) {
105 $this->thumbUrl = $info['thumbUrl'];
106 } else {
107 $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
108 }
109 $this->hashLevels = isset( $info['hashLevels'] )
110 ? $info['hashLevels']
111 : 2;
112 $this->deletedHashLevels = isset( $info['deletedHashLevels'] )
113 ? $info['deletedHashLevels']
114 : $this->hashLevels;
115 $this->transformVia404 = !empty( $info['transformVia404'] );
116 $this->zones = isset( $info['zones'] )
117 ? $info['zones']
118 : array();
119 // Give defaults for the basic zones...
120 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
121 if ( !isset( $this->zones[$zone] ) ) {
122 $this->zones[$zone] = array(
123 'container' => "{$this->name}-{$zone}",
124 'directory' => '' // container root
125 );
126 }
127 }
128 }
129
130 /**
131 * Get the file backend instance. Use this function wisely.
132 *
133 * @return FileBackend
134 */
135 public function getBackend() {
136 return $this->backend;
137 }
138
139 /**
140 * Get an explanatory message if this repo is read-only.
141 * This checks if an administrator disabled writes to the backend.
142 *
143 * @return string|bool Returns false if the repo is not read-only
144 */
145 public function getReadOnlyReason() {
146 return $this->backend->getReadOnlyReason();
147 }
148
149 /**
150 * Check if a single zone or list of zones is defined for usage
151 *
152 * @param $doZones Array Only do a particular zones
153 * @throws MWException
154 * @return Status
155 */
156 protected function initZones( $doZones = array() ) {
157 $status = $this->newGood();
158 foreach ( (array)$doZones as $zone ) {
159 $root = $this->getZonePath( $zone );
160 if ( $root === null ) {
161 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
162 }
163 }
164 return $status;
165 }
166
167 /**
168 * Take all available measures to prevent web accessibility of new deleted
169 * directories, in case the user has not configured offline storage
170 *
171 * @param $dir string
172 * @return void
173 */
174 protected function initDeletedDir( $dir ) {
175 $this->backend->secure( // prevent web access & dir listings
176 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
177 }
178
179 /**
180 * Determine if a string is an mwrepo:// URL
181 *
182 * @param $url string
183 * @return bool
184 */
185 public static function isVirtualUrl( $url ) {
186 return substr( $url, 0, 9 ) == 'mwrepo://';
187 }
188
189 /**
190 * Get a URL referring to this repository, with the private mwrepo protocol.
191 * The suffix, if supplied, is considered to be unencoded, and will be
192 * URL-encoded before being returned.
193 *
194 * @param $suffix string|bool
195 * @return string
196 */
197 public function getVirtualUrl( $suffix = false ) {
198 $path = 'mwrepo://' . $this->name;
199 if ( $suffix !== false ) {
200 $path .= '/' . rawurlencode( $suffix );
201 }
202 return $path;
203 }
204
205 /**
206 * Get the URL corresponding to one of the four basic zones
207 *
208 * @param $zone String: one of: public, deleted, temp, thumb
209 * @return String or false
210 */
211 public function getZoneUrl( $zone ) {
212 switch ( $zone ) {
213 case 'public':
214 return $this->url;
215 case 'temp':
216 return "{$this->url}/temp";
217 case 'deleted':
218 return false; // no public URL
219 case 'thumb':
220 return $this->thumbUrl;
221 default:
222 return false;
223 }
224 }
225
226 /**
227 * Get the backend storage path corresponding to a virtual URL.
228 * Use this function wisely.
229 *
230 * @param $url string
231 * @throws MWException
232 * @return string
233 */
234 public function resolveVirtualUrl( $url ) {
235 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
236 throw new MWException( __METHOD__.': unknown protocol' );
237 }
238 $bits = explode( '/', substr( $url, 9 ), 3 );
239 if ( count( $bits ) != 3 ) {
240 throw new MWException( __METHOD__.": invalid mwrepo URL: $url" );
241 }
242 list( $repo, $zone, $rel ) = $bits;
243 if ( $repo !== $this->name ) {
244 throw new MWException( __METHOD__.": fetching from a foreign repo is not supported" );
245 }
246 $base = $this->getZonePath( $zone );
247 if ( !$base ) {
248 throw new MWException( __METHOD__.": invalid zone: $zone" );
249 }
250 return $base . '/' . rawurldecode( $rel );
251 }
252
253 /**
254 * The the storage container and base path of a zone
255 *
256 * @param $zone string
257 * @return Array (container, base path) or (null, null)
258 */
259 protected function getZoneLocation( $zone ) {
260 if ( !isset( $this->zones[$zone] ) ) {
261 return array( null, null ); // bogus
262 }
263 return array( $this->zones[$zone]['container'], $this->zones[$zone]['directory'] );
264 }
265
266 /**
267 * Get the storage path corresponding to one of the zones
268 *
269 * @param $zone string
270 * @return string|null Returns null if the zone is not defined
271 */
272 public function getZonePath( $zone ) {
273 list( $container, $base ) = $this->getZoneLocation( $zone );
274 if ( $container === null || $base === null ) {
275 return null;
276 }
277 $backendName = $this->backend->getName();
278 if ( $base != '' ) { // may not be set
279 $base = "/{$base}";
280 }
281 return "mwstore://$backendName/{$container}{$base}";
282 }
283
284 /**
285 * Create a new File object from the local repository
286 *
287 * @param $title Mixed: Title object or string
288 * @param $time Mixed: Time at which the image was uploaded.
289 * If this is specified, the returned object will be an
290 * instance of the repository's old file class instead of a
291 * current file. Repositories not supporting version control
292 * should return false if this parameter is set.
293 * @return File|null A File, or null if passed an invalid Title
294 */
295 public function newFile( $title, $time = false ) {
296 $title = File::normalizeTitle( $title );
297 if ( !$title ) {
298 return null;
299 }
300 if ( $time ) {
301 if ( $this->oldFileFactory ) {
302 return call_user_func( $this->oldFileFactory, $title, $this, $time );
303 } else {
304 return false;
305 }
306 } else {
307 return call_user_func( $this->fileFactory, $title, $this );
308 }
309 }
310
311 /**
312 * Find an instance of the named file created at the specified time
313 * Returns false if the file does not exist. Repositories not supporting
314 * version control should return false if the time is specified.
315 *
316 * @param $title Mixed: Title object or string
317 * @param $options array Associative array of options:
318 * time: requested time for a specific file version, or false for the
319 * current version. An image object will be returned which was
320 * created at the specified time (which may be archived or current).
321 *
322 * ignoreRedirect: If true, do not follow file redirects
323 *
324 * private: If true, return restricted (deleted) files if the current
325 * user is allowed to view them. Otherwise, such files will not
326 * be found.
327 * @return File|bool False on failure
328 */
329 public function findFile( $title, $options = array() ) {
330 $title = File::normalizeTitle( $title );
331 if ( !$title ) {
332 return false;
333 }
334 $time = isset( $options['time'] ) ? $options['time'] : false;
335 # First try the current version of the file to see if it precedes the timestamp
336 $img = $this->newFile( $title );
337 if ( !$img ) {
338 return false;
339 }
340 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
341 return $img;
342 }
343 # Now try an old version of the file
344 if ( $time !== false ) {
345 $img = $this->newFile( $title, $time );
346 if ( $img && $img->exists() ) {
347 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
348 return $img; // always OK
349 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
350 return $img;
351 }
352 }
353 }
354
355 # Now try redirects
356 if ( !empty( $options['ignoreRedirect'] ) ) {
357 return false;
358 }
359 $redir = $this->checkRedirect( $title );
360 if ( $redir && $title->getNamespace() == NS_FILE) {
361 $img = $this->newFile( $redir );
362 if ( !$img ) {
363 return false;
364 }
365 if ( $img->exists() ) {
366 $img->redirectedFrom( $title->getDBkey() );
367 return $img;
368 }
369 }
370 return false;
371 }
372
373 /**
374 * Find many files at once.
375 *
376 * @param $items array An array of titles, or an array of findFile() options with
377 * the "title" option giving the title. Example:
378 *
379 * $findItem = array( 'title' => $title, 'private' => true );
380 * $findBatch = array( $findItem );
381 * $repo->findFiles( $findBatch );
382 * @return array
383 */
384 public function findFiles( array $items ) {
385 $result = array();
386 foreach ( $items as $item ) {
387 if ( is_array( $item ) ) {
388 $title = $item['title'];
389 $options = $item;
390 unset( $options['title'] );
391 } else {
392 $title = $item;
393 $options = array();
394 }
395 $file = $this->findFile( $title, $options );
396 if ( $file ) {
397 $result[$file->getTitle()->getDBkey()] = $file;
398 }
399 }
400 return $result;
401 }
402
403 /**
404 * Find an instance of the file with this key, created at the specified time
405 * Returns false if the file does not exist. Repositories not supporting
406 * version control should return false if the time is specified.
407 *
408 * @param $sha1 String base 36 SHA-1 hash
409 * @param $options array Option array, same as findFile().
410 * @return File|bool False on failure
411 */
412 public function findFileFromKey( $sha1, $options = array() ) {
413 $time = isset( $options['time'] ) ? $options['time'] : false;
414 # First try to find a matching current version of a file...
415 if ( $this->fileFactoryKey ) {
416 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
417 } else {
418 return false; // find-by-sha1 not supported
419 }
420 if ( $img && $img->exists() ) {
421 return $img;
422 }
423 # Now try to find a matching old version of a file...
424 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
425 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
426 if ( $img && $img->exists() ) {
427 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
428 return $img; // always OK
429 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
430 return $img;
431 }
432 }
433 }
434 return false;
435 }
436
437 /**
438 * Get an array or iterator of file objects for files that have a given
439 * SHA-1 content hash.
440 *
441 * STUB
442 * @param $hash
443 * @return array
444 */
445 public function findBySha1( $hash ) {
446 return array();
447 }
448
449 /**
450 * Get the public root URL of the repository
451 *
452 * @return string
453 */
454 public function getRootUrl() {
455 return $this->url;
456 }
457
458 /**
459 * Get the URL of thumb.php
460 *
461 * @return string
462 */
463 public function getThumbScriptUrl() {
464 return $this->thumbScriptUrl;
465 }
466
467 /**
468 * Returns true if the repository can transform files via a 404 handler
469 *
470 * @return bool
471 */
472 public function canTransformVia404() {
473 return $this->transformVia404;
474 }
475
476 /**
477 * Get the name of an image from its title object
478 *
479 * @param $title Title
480 * @return String
481 */
482 public function getNameFromTitle( Title $title ) {
483 global $wgContLang;
484 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
485 $name = $title->getUserCaseDBKey();
486 if ( $this->initialCapital ) {
487 $name = $wgContLang->ucfirst( $name );
488 }
489 } else {
490 $name = $title->getDBkey();
491 }
492 return $name;
493 }
494
495 /**
496 * Get the public zone root storage directory of the repository
497 *
498 * @return string
499 */
500 public function getRootDirectory() {
501 return $this->getZonePath( 'public' );
502 }
503
504 /**
505 * Get a relative path including trailing slash, e.g. f/fa/
506 * If the repo is not hashed, returns an empty string
507 *
508 * @param $name string Name of file
509 * @return string
510 */
511 public function getHashPath( $name ) {
512 return self::getHashPathForLevel( $name, $this->hashLevels );
513 }
514
515 /**
516 * Get a relative path including trailing slash, e.g. f/fa/
517 * If the repo is not hashed, returns an empty string
518 *
519 * @param $suffix string Basename of file from FileRepo::storeTemp()
520 * @return string
521 */
522 public function getTempHashPath( $suffix ) {
523 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
524 $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp
525 return self::getHashPathForLevel( $name, $this->hashLevels );
526 }
527
528 /**
529 * @param $name
530 * @param $levels
531 * @return string
532 */
533 protected static function getHashPathForLevel( $name, $levels ) {
534 if ( $levels == 0 ) {
535 return '';
536 } else {
537 $hash = md5( $name );
538 $path = '';
539 for ( $i = 1; $i <= $levels; $i++ ) {
540 $path .= substr( $hash, 0, $i ) . '/';
541 }
542 return $path;
543 }
544 }
545
546 /**
547 * Get the number of hash directory levels
548 *
549 * @return integer
550 */
551 public function getHashLevels() {
552 return $this->hashLevels;
553 }
554
555 /**
556 * Get the name of this repository, as specified by $info['name]' to the constructor
557 *
558 * @return string
559 */
560 public function getName() {
561 return $this->name;
562 }
563
564 /**
565 * Make an url to this repo
566 *
567 * @param $query mixed Query string to append
568 * @param $entry string Entry point; defaults to index
569 * @return string|bool False on failure
570 */
571 public function makeUrl( $query = '', $entry = 'index' ) {
572 if ( isset( $this->scriptDirUrl ) ) {
573 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
574 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
575 }
576 return false;
577 }
578
579 /**
580 * Get the URL of an image description page. May return false if it is
581 * unknown or not applicable. In general this should only be called by the
582 * File class, since it may return invalid results for certain kinds of
583 * repositories. Use File::getDescriptionUrl() in user code.
584 *
585 * In particular, it uses the article paths as specified to the repository
586 * constructor, whereas local repositories use the local Title functions.
587 *
588 * @param $name string
589 * @return string
590 */
591 public function getDescriptionUrl( $name ) {
592 $encName = wfUrlencode( $name );
593 if ( !is_null( $this->descBaseUrl ) ) {
594 # "http://example.com/wiki/Image:"
595 return $this->descBaseUrl . $encName;
596 }
597 if ( !is_null( $this->articleUrl ) ) {
598 # "http://example.com/wiki/$1"
599 #
600 # We use "Image:" as the canonical namespace for
601 # compatibility across all MediaWiki versions.
602 return str_replace( '$1',
603 "Image:$encName", $this->articleUrl );
604 }
605 if ( !is_null( $this->scriptDirUrl ) ) {
606 # "http://example.com/w"
607 #
608 # We use "Image:" as the canonical namespace for
609 # compatibility across all MediaWiki versions,
610 # and just sort of hope index.php is right. ;)
611 return $this->makeUrl( "title=Image:$encName" );
612 }
613 return false;
614 }
615
616 /**
617 * Get the URL of the content-only fragment of the description page. For
618 * MediaWiki this means action=render. This should only be called by the
619 * repository's file class, since it may return invalid results. User code
620 * should use File::getDescriptionText().
621 *
622 * @param $name String: name of image to fetch
623 * @param $lang String: language to fetch it in, if any.
624 * @return string
625 */
626 public function getDescriptionRenderUrl( $name, $lang = null ) {
627 $query = 'action=render';
628 if ( !is_null( $lang ) ) {
629 $query .= '&uselang=' . $lang;
630 }
631 if ( isset( $this->scriptDirUrl ) ) {
632 return $this->makeUrl(
633 'title=' .
634 wfUrlencode( 'Image:' . $name ) .
635 "&$query" );
636 } else {
637 $descUrl = $this->getDescriptionUrl( $name );
638 if ( $descUrl ) {
639 return wfAppendQuery( $descUrl, $query );
640 } else {
641 return false;
642 }
643 }
644 }
645
646 /**
647 * Get the URL of the stylesheet to apply to description pages
648 *
649 * @return string|bool False on failure
650 */
651 public function getDescriptionStylesheetUrl() {
652 if ( isset( $this->scriptDirUrl ) ) {
653 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
654 wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
655 }
656 return false;
657 }
658
659 /**
660 * Store a file to a given destination.
661 *
662 * @param $srcPath String: source FS path, storage path, or virtual URL
663 * @param $dstZone String: destination zone
664 * @param $dstRel String: destination relative path
665 * @param $flags Integer: bitwise combination of the following flags:
666 * self::DELETE_SOURCE Delete the source file after upload
667 * self::OVERWRITE Overwrite an existing destination file instead of failing
668 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
669 * same contents as the source
670 * self::SKIP_LOCKING Skip any file locking when doing the store
671 * @return FileRepoStatus
672 */
673 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
674 $this->assertWritableRepo(); // fail out if read-only
675
676 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
677 if ( $status->successCount == 0 ) {
678 $status->ok = false;
679 }
680
681 return $status;
682 }
683
684 /**
685 * Store a batch of files
686 *
687 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
688 * @param $flags Integer: bitwise combination of the following flags:
689 * self::DELETE_SOURCE Delete the source file after upload
690 * self::OVERWRITE Overwrite an existing destination file instead of failing
691 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
692 * same contents as the source
693 * self::SKIP_LOCKING Skip any file locking when doing the store
694 * @throws MWException
695 * @return FileRepoStatus
696 */
697 public function storeBatch( array $triplets, $flags = 0 ) {
698 $this->assertWritableRepo(); // fail out if read-only
699
700 $status = $this->newGood();
701 $backend = $this->backend; // convenience
702
703 $operations = array();
704 $sourceFSFilesToDelete = array(); // cleanup for disk source files
705 // Validate each triplet and get the store operation...
706 foreach ( $triplets as $triplet ) {
707 list( $srcPath, $dstZone, $dstRel ) = $triplet;
708 wfDebug( __METHOD__
709 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
710 );
711
712 // Resolve destination path
713 $root = $this->getZonePath( $dstZone );
714 if ( !$root ) {
715 throw new MWException( "Invalid zone: $dstZone" );
716 }
717 if ( !$this->validateFilename( $dstRel ) ) {
718 throw new MWException( 'Validation error in $dstRel' );
719 }
720 $dstPath = "$root/$dstRel";
721 $dstDir = dirname( $dstPath );
722 // Create destination directories for this triplet
723 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
724 return $this->newFatal( 'directorycreateerror', $dstDir );
725 }
726
727 if ( $dstZone == 'deleted' ) {
728 $this->initDeletedDir( $dstDir );
729 }
730
731 // Resolve source to a storage path if virtual
732 $srcPath = $this->resolveToStoragePath( $srcPath );
733
734 // Get the appropriate file operation
735 if ( FileBackend::isStoragePath( $srcPath ) ) {
736 $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
737 } else {
738 $opName = 'store';
739 if ( $flags & self::DELETE_SOURCE ) {
740 $sourceFSFilesToDelete[] = $srcPath;
741 }
742 }
743 $operations[] = array(
744 'op' => $opName,
745 'src' => $srcPath,
746 'dst' => $dstPath,
747 'overwrite' => $flags & self::OVERWRITE,
748 'overwriteSame' => $flags & self::OVERWRITE_SAME,
749 );
750 }
751
752 // Execute the store operation for each triplet
753 $opts = array( 'force' => true );
754 if ( $flags & self::SKIP_LOCKING ) {
755 $opts['nonLocking'] = true;
756 }
757 $status->merge( $backend->doOperations( $operations, $opts ) );
758 // Cleanup for disk source files...
759 foreach ( $sourceFSFilesToDelete as $file ) {
760 wfSuppressWarnings();
761 unlink( $file ); // FS cleanup
762 wfRestoreWarnings();
763 }
764
765 return $status;
766 }
767
768 /**
769 * Deletes a batch of files.
770 * Each file can be a (zone, rel) pair, virtual url, storage path.
771 * It will try to delete each file, but ignores any errors that may occur.
772 *
773 * @param $files array List of files to delete
774 * @param $flags Integer: bitwise combination of the following flags:
775 * self::SKIP_LOCKING Skip any file locking when doing the deletions
776 * @return FileRepoStatus
777 */
778 public function cleanupBatch( array $files, $flags = 0 ) {
779 $this->assertWritableRepo(); // fail out if read-only
780
781 $status = $this->newGood();
782
783 $operations = array();
784 foreach ( $files as $path ) {
785 if ( is_array( $path ) ) {
786 // This is a pair, extract it
787 list( $zone, $rel ) = $path;
788 $path = $this->getZonePath( $zone ) . "/$rel";
789 } else {
790 // Resolve source to a storage path if virtual
791 $path = $this->resolveToStoragePath( $path );
792 }
793 $operations[] = array( 'op' => 'delete', 'src' => $path );
794 }
795 // Actually delete files from storage...
796 $opts = array( 'force' => true );
797 if ( $flags & self::SKIP_LOCKING ) {
798 $opts['nonLocking'] = true;
799 }
800 $status->merge( $this->backend->doOperations( $operations, $opts ) );
801
802 return $status;
803 }
804
805 /**
806 * Import a file from the local file system into the repo.
807 * This does no locking nor journaling and overrides existing files.
808 * This function can be used to write to otherwise read-only foreign repos.
809 * This is intended for copying generated thumbnails into the repo.
810 *
811 * @param $src string File system path
812 * @param $dst string Virtual URL or storage path
813 * @return FileRepoStatus
814 */
815 final public function quickImport( $src, $dst ) {
816 return $this->quickImportBatch( array( array( $src, $dst ) ) );
817 }
818
819 /**
820 * Purge a file from the repo. This does no locking nor journaling.
821 * This function can be used to write to otherwise read-only foreign repos.
822 * This is intended for purging thumbnails.
823 *
824 * @param $path string Virtual URL or storage path
825 * @return FileRepoStatus
826 */
827 final public function quickPurge( $path ) {
828 return $this->quickPurgeBatch( array( $path ) );
829 }
830
831 /**
832 * Deletes a directory if empty.
833 * This function can be used to write to otherwise read-only foreign repos.
834 *
835 * @param $dir string Virtual URL (or storage path) of directory to clean
836 * @return Status
837 */
838 public function quickCleanDir( $dir ) {
839 $status = $this->newGood();
840 $status->merge( $this->backend->clean(
841 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
842
843 return $status;
844 }
845
846 /**
847 * Import a batch of files from the local file system into the repo.
848 * This does no locking nor journaling and overrides existing files.
849 * This function can be used to write to otherwise read-only foreign repos.
850 * This is intended for copying generated thumbnails into the repo.
851 *
852 * @param $pairs Array List of tuples (file system path, virtual URL or storage path)
853 * @return FileRepoStatus
854 */
855 public function quickImportBatch( array $pairs ) {
856 $status = $this->newGood();
857 $operations = array();
858 foreach ( $pairs as $pair ) {
859 list ( $src, $dst ) = $pair;
860 $operations[] = array(
861 'op' => 'store',
862 'src' => $src,
863 'dst' => $this->resolveToStoragePath( $dst )
864 );
865 $this->backend->prepare( array( 'dir' => dirname( $dst ) ) );
866 }
867 $status->merge( $this->backend->doQuickOperations( $operations ) );
868
869 return $status;
870 }
871
872 /**
873 * Purge a batch of files from the repo.
874 * This function can be used to write to otherwise read-only foreign repos.
875 * This does no locking nor journaling and is intended for purging thumbnails.
876 *
877 * @param $paths Array List of virtual URLs or storage paths
878 * @return FileRepoStatus
879 */
880 public function quickPurgeBatch( array $paths ) {
881 $status = $this->newGood();
882 $operations = array();
883 foreach ( $paths as $path ) {
884 $operations[] = array(
885 'op' => 'delete',
886 'src' => $this->resolveToStoragePath( $path ),
887 'ignoreMissingSource' => true
888 );
889 }
890 $status->merge( $this->backend->doQuickOperations( $operations ) );
891
892 return $status;
893 }
894
895 /**
896 * Pick a random name in the temp zone and store a file to it.
897 * Returns a FileRepoStatus object with the file Virtual URL in the value,
898 * file can later be disposed using FileRepo::freeTemp().
899 *
900 * @param $originalName String: the base name of the file as specified
901 * by the user. The file extension will be maintained.
902 * @param $srcPath String: the current location of the file.
903 * @return FileRepoStatus object with the URL in the value.
904 */
905 public function storeTemp( $originalName, $srcPath ) {
906 $this->assertWritableRepo(); // fail out if read-only
907
908 $date = gmdate( "YmdHis" );
909 $hashPath = $this->getHashPath( $originalName );
910 $dstRel = "{$hashPath}{$date}!{$originalName}";
911 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
912
913 $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
914 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
915
916 return $result;
917 }
918
919 /**
920 * Concatenate a list of files into a target file location.
921 *
922 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
923 * @param $dstPath String Target file system path
924 * @param $flags Integer: bitwise combination of the following flags:
925 * self::DELETE_SOURCE Delete the source files
926 * @return FileRepoStatus
927 */
928 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
929 $this->assertWritableRepo(); // fail out if read-only
930
931 $status = $this->newGood();
932
933 $sources = array();
934 $deleteOperations = array(); // post-concatenate ops
935 foreach ( $srcPaths as $srcPath ) {
936 // Resolve source to a storage path if virtual
937 $source = $this->resolveToStoragePath( $srcPath );
938 $sources[] = $source; // chunk to merge
939 if ( $flags & self::DELETE_SOURCE ) {
940 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
941 }
942 }
943
944 // Concatenate the chunks into one FS file
945 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
946 $status->merge( $this->backend->concatenate( $params ) );
947 if ( !$status->isOK() ) {
948 return $status;
949 }
950
951 // Delete the sources if required
952 if ( $deleteOperations ) {
953 $opts = array( 'force' => true );
954 $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
955 }
956
957 // Make sure status is OK, despite any $deleteOperations fatals
958 $status->setResult( true );
959
960 return $status;
961 }
962
963 /**
964 * Remove a temporary file or mark it for garbage collection
965 *
966 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
967 * @return Boolean: true on success, false on failure
968 */
969 public function freeTemp( $virtualUrl ) {
970 $this->assertWritableRepo(); // fail out if read-only
971
972 $temp = "mwrepo://{$this->name}/temp";
973 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
974 wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
975 return false;
976 }
977 $path = $this->resolveVirtualUrl( $virtualUrl );
978
979 return $this->cleanupBatch( array( $path ), self::SKIP_LOCKING )->isOK();
980 }
981
982 /**
983 * Copy or move a file either from a storage path, virtual URL,
984 * or FS path, into this repository at the specified destination location.
985 *
986 * Returns a FileRepoStatus object. On success, the value contains "new" or
987 * "archived", to indicate whether the file was new with that name.
988 *
989 * @param $srcPath String: the source FS path, storage path, or URL
990 * @param $dstRel String: the destination relative path
991 * @param $archiveRel String: the relative path where the existing file is to
992 * be archived, if there is one. Relative to the public zone root.
993 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
994 * that the source file should be deleted if possible
995 * @return FileRepoStatus
996 */
997 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
998 $this->assertWritableRepo(); // fail out if read-only
999
1000 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1001 if ( $status->successCount == 0 ) {
1002 $status->ok = false;
1003 }
1004 if ( isset( $status->value[0] ) ) {
1005 $status->value = $status->value[0];
1006 } else {
1007 $status->value = false;
1008 }
1009
1010 return $status;
1011 }
1012
1013 /**
1014 * Publish a batch of files
1015 *
1016 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1017 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1018 * that the source files should be deleted if possible
1019 * @throws MWException
1020 * @return FileRepoStatus
1021 */
1022 public function publishBatch( array $triplets, $flags = 0 ) {
1023 $this->assertWritableRepo(); // fail out if read-only
1024
1025 $backend = $this->backend; // convenience
1026 // Try creating directories
1027 $status = $this->initZones( 'public' );
1028 if ( !$status->isOK() ) {
1029 return $status;
1030 }
1031
1032 $status = $this->newGood( array() );
1033
1034 $operations = array();
1035 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1036 // Validate each triplet and get the store operation...
1037 foreach ( $triplets as $i => $triplet ) {
1038 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1039 // Resolve source to a storage path if virtual
1040 $srcPath = $this->resolveToStoragePath( $srcPath );
1041 if ( !$this->validateFilename( $dstRel ) ) {
1042 throw new MWException( 'Validation error in $dstRel' );
1043 }
1044 if ( !$this->validateFilename( $archiveRel ) ) {
1045 throw new MWException( 'Validation error in $archiveRel' );
1046 }
1047
1048 $publicRoot = $this->getZonePath( 'public' );
1049 $dstPath = "$publicRoot/$dstRel";
1050 $archivePath = "$publicRoot/$archiveRel";
1051
1052 $dstDir = dirname( $dstPath );
1053 $archiveDir = dirname( $archivePath );
1054 // Abort immediately on directory creation errors since they're likely to be repetitive
1055 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1056 return $this->newFatal( 'directorycreateerror', $dstDir );
1057 }
1058 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1059 return $this->newFatal( 'directorycreateerror', $archiveDir );
1060 }
1061
1062 // Archive destination file if it exists
1063 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1064 // Check if the archive file exists
1065 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1066 // unlinks the destination file if it exists. DB-based synchronisation in
1067 // publishBatch's caller should prevent races. In Windows there's no
1068 // problem because the rename primitive fails if the destination exists.
1069 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1070 $operations[] = array( 'op' => 'null' );
1071 continue;
1072 } else {
1073 $operations[] = array(
1074 'op' => 'move',
1075 'src' => $dstPath,
1076 'dst' => $archivePath
1077 );
1078 }
1079 $status->value[$i] = 'archived';
1080 } else {
1081 $status->value[$i] = 'new';
1082 }
1083 // Copy (or move) the source file to the destination
1084 if ( FileBackend::isStoragePath( $srcPath ) ) {
1085 if ( $flags & self::DELETE_SOURCE ) {
1086 $operations[] = array(
1087 'op' => 'move',
1088 'src' => $srcPath,
1089 'dst' => $dstPath
1090 );
1091 } else {
1092 $operations[] = array(
1093 'op' => 'copy',
1094 'src' => $srcPath,
1095 'dst' => $dstPath
1096 );
1097 }
1098 } else { // FS source path
1099 $operations[] = array(
1100 'op' => 'store',
1101 'src' => $srcPath,
1102 'dst' => $dstPath
1103 );
1104 if ( $flags & self::DELETE_SOURCE ) {
1105 $sourceFSFilesToDelete[] = $srcPath;
1106 }
1107 }
1108 }
1109
1110 // Execute the operations for each triplet
1111 $opts = array( 'force' => true );
1112 $status->merge( $backend->doOperations( $operations, $opts ) );
1113 // Cleanup for disk source files...
1114 foreach ( $sourceFSFilesToDelete as $file ) {
1115 wfSuppressWarnings();
1116 unlink( $file ); // FS cleanup
1117 wfRestoreWarnings();
1118 }
1119
1120 return $status;
1121 }
1122
1123 /**
1124 * Deletes a directory if empty.
1125 *
1126 * @param $dir string Virtual URL (or storage path) of directory to clean
1127 * @return Status
1128 */
1129 public function cleanDir( $dir ) {
1130 $this->assertWritableRepo(); // fail out if read-only
1131
1132 $status = $this->newGood();
1133 $status->merge( $this->backend->clean(
1134 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1135
1136 return $status;
1137 }
1138
1139 /**
1140 * Checks existence of a a file
1141 *
1142 * @param $file string Virtual URL (or storage path) of file to check
1143 * @return bool
1144 */
1145 public function fileExists( $file ) {
1146 $result = $this->fileExistsBatch( array( $file ) );
1147 return $result[0];
1148 }
1149
1150 /**
1151 * Checks existence of an array of files.
1152 *
1153 * @param $files Array: Virtual URLs (or storage paths) of files to check
1154 * @return array|bool Either array of files and existence flags, or false
1155 */
1156 public function fileExistsBatch( array $files ) {
1157 $result = array();
1158 foreach ( $files as $key => $file ) {
1159 $file = $this->resolveToStoragePath( $file );
1160 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1161 }
1162 return $result;
1163 }
1164
1165 /**
1166 * Move a file to the deletion archive.
1167 * If no valid deletion archive exists, this may either delete the file
1168 * or throw an exception, depending on the preference of the repository
1169 *
1170 * @param $srcRel Mixed: relative path for the file to be deleted
1171 * @param $archiveRel Mixed: relative path for the archive location.
1172 * Relative to a private archive directory.
1173 * @return FileRepoStatus object
1174 */
1175 public function delete( $srcRel, $archiveRel ) {
1176 $this->assertWritableRepo(); // fail out if read-only
1177
1178 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1179 }
1180
1181 /**
1182 * Move a group of files to the deletion archive.
1183 *
1184 * If no valid deletion archive is configured, this may either delete the
1185 * file or throw an exception, depending on the preference of the repository.
1186 *
1187 * The overwrite policy is determined by the repository -- currently LocalRepo
1188 * assumes a naming scheme in the deleted zone based on content hash, as
1189 * opposed to the public zone which is assumed to be unique.
1190 *
1191 * @param $sourceDestPairs Array of source/destination pairs. Each element
1192 * is a two-element array containing the source file path relative to the
1193 * public root in the first element, and the archive file path relative
1194 * to the deleted zone root in the second element.
1195 * @throws MWException
1196 * @return FileRepoStatus
1197 */
1198 public function deleteBatch( array $sourceDestPairs ) {
1199 $this->assertWritableRepo(); // fail out if read-only
1200
1201 // Try creating directories
1202 $status = $this->initZones( array( 'public', 'deleted' ) );
1203 if ( !$status->isOK() ) {
1204 return $status;
1205 }
1206
1207 $status = $this->newGood();
1208
1209 $backend = $this->backend; // convenience
1210 $operations = array();
1211 // Validate filenames and create archive directories
1212 foreach ( $sourceDestPairs as $pair ) {
1213 list( $srcRel, $archiveRel ) = $pair;
1214 if ( !$this->validateFilename( $srcRel ) ) {
1215 throw new MWException( __METHOD__.':Validation error in $srcRel' );
1216 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1217 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
1218 }
1219
1220 $publicRoot = $this->getZonePath( 'public' );
1221 $srcPath = "{$publicRoot}/$srcRel";
1222
1223 $deletedRoot = $this->getZonePath( 'deleted' );
1224 $archivePath = "{$deletedRoot}/{$archiveRel}";
1225 $archiveDir = dirname( $archivePath ); // does not touch FS
1226
1227 // Create destination directories
1228 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1229 return $this->newFatal( 'directorycreateerror', $archiveDir );
1230 }
1231 $this->initDeletedDir( $archiveDir );
1232
1233 $operations[] = array(
1234 'op' => 'move',
1235 'src' => $srcPath,
1236 'dst' => $archivePath,
1237 // We may have 2+ identical files being deleted,
1238 // all of which will map to the same destination file
1239 'overwriteSame' => true // also see bug 31792
1240 );
1241 }
1242
1243 // Move the files by execute the operations for each pair.
1244 // We're now committed to returning an OK result, which will
1245 // lead to the files being moved in the DB also.
1246 $opts = array( 'force' => true );
1247 $status->merge( $backend->doOperations( $operations, $opts ) );
1248
1249 return $status;
1250 }
1251
1252 /**
1253 * Delete files in the deleted directory if they are not referenced in the filearchive table
1254 *
1255 * STUB
1256 */
1257 public function cleanupDeletedBatch( array $storageKeys ) {
1258 $this->assertWritableRepo();
1259 }
1260
1261 /**
1262 * Get a relative path for a deletion archive key,
1263 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1264 *
1265 * @param $key string
1266 * @return string
1267 */
1268 public function getDeletedHashPath( $key ) {
1269 $path = '';
1270 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1271 $path .= $key[$i] . '/';
1272 }
1273 return $path;
1274 }
1275
1276 /**
1277 * If a path is a virtual URL, resolve it to a storage path.
1278 * Otherwise, just return the path as it is.
1279 *
1280 * @param $path string
1281 * @return string
1282 * @throws MWException
1283 */
1284 protected function resolveToStoragePath( $path ) {
1285 if ( $this->isVirtualUrl( $path ) ) {
1286 return $this->resolveVirtualUrl( $path );
1287 }
1288 return $path;
1289 }
1290
1291 /**
1292 * Get a local FS copy of a file with a given virtual URL/storage path.
1293 * Temporary files may be purged when the file object falls out of scope.
1294 *
1295 * @param $virtualUrl string
1296 * @return TempFSFile|null Returns null on failure
1297 */
1298 public function getLocalCopy( $virtualUrl ) {
1299 $path = $this->resolveToStoragePath( $virtualUrl );
1300 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1301 }
1302
1303 /**
1304 * Get a local FS file with a given virtual URL/storage path.
1305 * The file is either an original or a copy. It should not be changed.
1306 * Temporary files may be purged when the file object falls out of scope.
1307 *
1308 * @param $virtualUrl string
1309 * @return FSFile|null Returns null on failure.
1310 */
1311 public function getLocalReference( $virtualUrl ) {
1312 $path = $this->resolveToStoragePath( $virtualUrl );
1313 return $this->backend->getLocalReference( array( 'src' => $path ) );
1314 }
1315
1316 /**
1317 * Get properties of a file with a given virtual URL/storage path.
1318 * Properties should ultimately be obtained via FSFile::getProps().
1319 *
1320 * @param $virtualUrl string
1321 * @return Array
1322 */
1323 public function getFileProps( $virtualUrl ) {
1324 $path = $this->resolveToStoragePath( $virtualUrl );
1325 return $this->backend->getFileProps( array( 'src' => $path ) );
1326 }
1327
1328 /**
1329 * Get the timestamp of a file with a given virtual URL/storage path
1330 *
1331 * @param $virtualUrl string
1332 * @return string|bool False on failure
1333 */
1334 public function getFileTimestamp( $virtualUrl ) {
1335 $path = $this->resolveToStoragePath( $virtualUrl );
1336 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1337 }
1338
1339 /**
1340 * Get the sha1 of a file with a given virtual URL/storage path
1341 *
1342 * @param $virtualUrl string
1343 * @return string|bool
1344 */
1345 public function getFileSha1( $virtualUrl ) {
1346 $path = $this->resolveToStoragePath( $virtualUrl );
1347 $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
1348 if ( !$tmpFile ) {
1349 return false;
1350 }
1351 return $tmpFile->getSha1Base36();
1352 }
1353
1354 /**
1355 * Attempt to stream a file with the given virtual URL/storage path
1356 *
1357 * @param $virtualUrl string
1358 * @param $headers Array Additional HTTP headers to send on success
1359 * @return bool Success
1360 */
1361 public function streamFile( $virtualUrl, $headers = array() ) {
1362 $path = $this->resolveToStoragePath( $virtualUrl );
1363 $params = array( 'src' => $path, 'headers' => $headers );
1364 return $this->backend->streamFile( $params )->isOK();
1365 }
1366
1367 /**
1368 * Call a callback function for every public regular file in the repository.
1369 * This only acts on the current version of files, not any old versions.
1370 * May use either the database or the filesystem.
1371 *
1372 * @param $callback Array|string
1373 * @return void
1374 */
1375 public function enumFiles( $callback ) {
1376 $this->enumFilesInStorage( $callback );
1377 }
1378
1379 /**
1380 * Call a callback function for every public file in the repository.
1381 * May use either the database or the filesystem.
1382 *
1383 * @param $callback Array|string
1384 * @return void
1385 */
1386 protected function enumFilesInStorage( $callback ) {
1387 $publicRoot = $this->getZonePath( 'public' );
1388 $numDirs = 1 << ( $this->hashLevels * 4 );
1389 // Use a priori assumptions about directory structure
1390 // to reduce the tree height of the scanning process.
1391 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1392 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1393 $path = $publicRoot;
1394 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1395 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1396 }
1397 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1398 foreach ( $iterator as $name ) {
1399 // Each item returned is a public file
1400 call_user_func( $callback, "{$path}/{$name}" );
1401 }
1402 }
1403 }
1404
1405 /**
1406 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1407 *
1408 * @param $filename string
1409 * @return bool
1410 */
1411 public function validateFilename( $filename ) {
1412 if ( strval( $filename ) == '' ) {
1413 return false;
1414 }
1415 return FileBackend::isPathTraversalFree( $filename );
1416 }
1417
1418 /**
1419 * Get a callback function to use for cleaning error message parameters
1420 *
1421 * @return Array
1422 */
1423 function getErrorCleanupFunction() {
1424 switch ( $this->pathDisclosureProtection ) {
1425 case 'none':
1426 case 'simple': // b/c
1427 $callback = array( $this, 'passThrough' );
1428 break;
1429 default: // 'paranoid'
1430 $callback = array( $this, 'paranoidClean' );
1431 }
1432 return $callback;
1433 }
1434
1435 /**
1436 * Path disclosure protection function
1437 *
1438 * @param $param string
1439 * @return string
1440 */
1441 function paranoidClean( $param ) {
1442 return '[hidden]';
1443 }
1444
1445 /**
1446 * Path disclosure protection function
1447 *
1448 * @param $param string
1449 * @return string
1450 */
1451 function passThrough( $param ) {
1452 return $param;
1453 }
1454
1455 /**
1456 * Create a new fatal error
1457 *
1458 * @return FileRepoStatus
1459 */
1460 public function newFatal( $message /*, parameters...*/ ) {
1461 $params = func_get_args();
1462 array_unshift( $params, $this );
1463 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1464 }
1465
1466 /**
1467 * Create a new good result
1468 *
1469 * @param $value null|string
1470 * @return FileRepoStatus
1471 */
1472 public function newGood( $value = null ) {
1473 return FileRepoStatus::newGood( $this, $value );
1474 }
1475
1476 /**
1477 * Checks if there is a redirect named as $title. If there is, return the
1478 * title object. If not, return false.
1479 * STUB
1480 *
1481 * @param $title Title of image
1482 * @return Bool
1483 */
1484 public function checkRedirect( Title $title ) {
1485 return false;
1486 }
1487
1488 /**
1489 * Invalidates image redirect cache related to that image
1490 * Doesn't do anything for repositories that don't support image redirects.
1491 *
1492 * STUB
1493 * @param $title Title of image
1494 */
1495 public function invalidateImageRedirect( Title $title ) {}
1496
1497 /**
1498 * Get the human-readable name of the repo
1499 *
1500 * @return string
1501 */
1502 public function getDisplayName() {
1503 // We don't name our own repo, return nothing
1504 if ( $this->isLocal() ) {
1505 return null;
1506 }
1507 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1508 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1509 }
1510
1511 /**
1512 * Returns true if this the local file repository.
1513 *
1514 * @return bool
1515 */
1516 public function isLocal() {
1517 return $this->getName() == 'local';
1518 }
1519
1520 /**
1521 * Get a key on the primary cache for this repository.
1522 * Returns false if the repository's cache is not accessible at this site.
1523 * The parameters are the parts of the key, as for wfMemcKey().
1524 *
1525 * STUB
1526 * @return bool
1527 */
1528 public function getSharedCacheKey( /*...*/ ) {
1529 return false;
1530 }
1531
1532 /**
1533 * Get a key for this repo in the local cache domain. These cache keys are
1534 * not shared with remote instances of the repo.
1535 * The parameters are the parts of the key, as for wfMemcKey().
1536 *
1537 * @return string
1538 */
1539 public function getLocalCacheKey( /*...*/ ) {
1540 $args = func_get_args();
1541 array_unshift( $args, 'filerepo', $this->getName() );
1542 return call_user_func_array( 'wfMemcKey', $args );
1543 }
1544
1545 /**
1546 * Get an temporary FileRepo associated with this repo.
1547 * Files will be created in the temp zone of this repo and
1548 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1549 * It will have the same backend as this repo.
1550 *
1551 * @return TempFileRepo
1552 */
1553 public function getTempRepo() {
1554 return new TempFileRepo( array(
1555 'name' => "{$this->name}-temp",
1556 'backend' => $this->backend,
1557 'zones' => array(
1558 'public' => array(
1559 'container' => $this->zones['temp']['container'],
1560 'directory' => $this->zones['temp']['directory']
1561 ),
1562 'thumb' => array(
1563 'container' => $this->zones['thumb']['container'],
1564 'directory' => ( $this->zones['thumb']['directory'] == '' )
1565 ? 'temp'
1566 : $this->zones['thumb']['directory'] . '/temp'
1567 )
1568 ),
1569 'url' => $this->getZoneUrl( 'temp' ),
1570 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1571 'hashLevels' => $this->hashLevels // performance
1572 ) );
1573 }
1574
1575 /**
1576 * Get an UploadStash associated with this repo.
1577 *
1578 * @return UploadStash
1579 */
1580 public function getUploadStash() {
1581 return new UploadStash( $this );
1582 }
1583
1584 /**
1585 * Throw an exception if this repo is read-only by design.
1586 * This does not and should not check getReadOnlyReason().
1587 *
1588 * @return void
1589 * @throws MWException
1590 */
1591 protected function assertWritableRepo() {}
1592 }
1593
1594 /**
1595 * FileRepo for temporary files created via FileRepo::getTempRepo()
1596 */
1597 class TempFileRepo extends FileRepo {
1598 public function getTempRepo() {
1599 throw new MWException( "Cannot get a temp repo from a temp repo." );
1600 }
1601 }